package me.yuxiaoyao.jpa.nativesql;

import me.yuxiaoyao.jpa.nativesql.mapper.JpaNativeSqlConverter;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * @author kerryzhang on 2020/12/16
 */


public class ApplicationContextStartedListener implements ApplicationListener<ApplicationStartedEvent> {

    private Set<String> packages;

    public ApplicationContextStartedListener(List<String> packages) {
        if (packages == null) {
            this.packages = new LinkedHashSet<>();
        } else {
            this.packages = new LinkedHashSet<>(packages);
        }
    }

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        if (packages == null || packages.isEmpty()) {
            packages = new LinkedHashSet<>();
            // use spring source
            // 这里设置DTO，或者注解可能所在的包名。默认使用 @SpringBootApplication 注解包下的所有
            Set<Object> allSources = event.getSpringApplication().getAllSources();
            for (Object source : allSources) {
                if (source instanceof Class) {
                    String name = ((Class<?>) source).getPackage().getName();
                    packages.add(name);
                }
            }
            // 这里设置DTO，或者注解可能所在的包名。默认使用 @SpringBootApplication 注解包下的所有
            JpaNativeSqlConverter.registerDefaultConverter(packages);
        }
    }

    public void setPackages(Set<String> packages) {
        this.packages = packages;
    }
}
